<template>
  <!-- inputSelect -->
  <div class="w100">
    <!-- :teleported="false" -->
    <el-select
      style="width: 100%"
      popper-class="selectChild"
      v-model="selectValue"
      reserve-keyword
      :placeholder="t('keys.pleaseSelect')"
      filterable
      :multiple="multipleFalg"
      collapse-tags
      collapse-tags-tooltip
      remote
      v-selectLoadMore="loadList"
      :disabled="selectObj.disabled"
      :clearable="selectObj.clearable"
      :remote-method="remoteMethod"
      @visible-change="focusEvent"
      @change="changeValue"
    >
      <!-- @focus="focusEvent"
      @visible-change="blurEvent" -->
      <!-- <el-option v-for="(item, index) in list" :key="index" :label="item[selectObj.keyName]" :value="item[selectObj.keyValue]"> </el-option> -->
      <el-option class="opsSpan" v-for="(item, index) in list" :key="index" :label="item[selectObj.keyName]" :value="item[selectObj.keyValue]">
        <span n v-for="(v, i) in selectObj.optionkeyName" :key="i" v-if="selectObj?.optionkeyName && selectObj?.optionkeyName.length"
          >{{ item[v] }} {{ i + 1 == selectObj.optionkeyName.length ? '' : '- ' }}</span
        >
      </el-option>

      <div class="loading" v-show="loading">{{ t('keys.Loading') }}...</div>
      <!-- <div class="loading" v-show="!canmore && list.length">加载完毕</div> -->
    </el-select>
  </div>
</template>

<script setup>
/* eslint-disable */
import { reactive, ref, nextTick, watch, computed } from 'vue'
import { ERR_OK } from 'config/statusCode'
import { getPageSelectApi } from '@/api/common'
import { useI18n } from 'vue-i18n'
const { t } = useI18n() // 中英文
const emit = defineEmits(['pageChange', 'update:modelValue'])

const props = defineProps({
  modelValue: {
    type: [Array, Number, String],
    default() {
      return ''
    }
  },
  selectObj: {
    type: Object,
    // default:'没值的时候我就显示啦~'
    default() {
      return {
        teleported: false,
        clearable: true,
        disabled: false,
        assignment: 'replaceId',
        keyName: 'empName',
        keyValue: 'empId',
        optionkeyName: ['empName', 'email'], // opstion显示的字段
        opsName: '', //  编辑回显list数据option的key的值
        opsValue: '', // 编辑回显list数据option的value的key的值
        Url: `/zemd/v1/${getTenantId()}/emp`,
        params: {}
      }
    }
  },
  selecOptionList: {
    // 选中的对象，用于编辑时回显
    type: Array,
    default: []
  },
  OptionKeyId: {
    // 选中的对象，唯一key名
    type: String,
    default: 'id'
  },
  multipleFalg: {
    // 是否多选 - 返回的modelValue 为数组[]
    type: Boolean,
    default: false
  }
})

const list = ref([])
list.value = props.selecOptionList
const blurvalue = ref(props.modelValue)
const listObj = reactive({})
const loading = ref(false) // 加载中
const selectValue = ref(props.modelValue)
const canmore = ref(true) // 加载完毕
const queryword = ref('')
const searchVal = reactive({
  page: 0,
  size: 20
})
const focusEvent = async (val) => {
  if (val) {
    queryword.value = ''
    canmore.value = true
    loading.value = true
    searchVal.page = 1
    list.value = []
    props.selectObj.params[props.selectObj.keyName] = queryword.value
    let data = {
      ...props.selectObj.params,
      ...searchVal
    }

    let res = await getPageSelectApi(props.selectObj.Url, data)
    if (res.code === ERR_OK) {
      if (props.selecOptionList.length > 0) {
        let delelist = some([...res.data.list, ...props.selecOptionList])
        list.value = [...list.value, ...delelist]
      } else {
        list.value = [...list.value, ...res.data.list]
      }
    }
    loading.value = false
  }
}
// 去除ID 相同的
const some = (tempArr) => {
  let some = []
  tempArr.forEach((el) => {
    if (!some.some((e) => (props.selectObj.keyValue ? e[props.selectObj.keyValue] == el[props.selectObj.keyValue] : e.id == el.id))) {
      some.push(el)
    }
  })

  return some
}

// 去除数组对象中重复值
const deteleObject = (tempArr) => {
  let result = []
  let obj = {}
  for (let i = 0; i < tempArr.length; i++) {
    if (!obj[tempArr[i][props.OptionKeyId]]) {
      result.push(tempArr[i])
      obj[tempArr[i][props.OptionKeyId]] = true
    }
  }
  return result
}

const remoteMethod = async (query) => {
  queryword.value = query
  if (query !== '') {
    canmore.value = true
    loading.value = true
    // 请求数据
    searchVal.page = 1
    list.value = []
    props.selectObj.params[props.selectObj.keyName] = query
    let data = {
      ...props.selectObj.params,
      ...searchVal
    }
    loading.value = true
    let res = await getPageSelectApi(props.selectObj.Url, data)
    if (res.code === ERR_OK) {
      if (props.selecOptionList.length > 0) {
        list.value = some(deteleObject([...list.value, ...res.data.list, ...props.selecOptionList]))
      } else {
        list.value = [...list.value, ...res.data.list]
      }
    }
    loading.value = false
    // canmore.value = false
  }
}

const loadList = async () => {
  if (!canmore.value) {
    return
  }
  if (loading.value) {
    return
  }
  searchVal.page++
  // 请求数据
  props.selectObj.params[props.selectObj.keyName] = queryword.value
  let data = {
    ...props.selectObj.params,
    ...searchVal
  }
  loading.value = true
  let res = await getPageSelectApi(props.selectObj.Url, data)
  if (res.code === ERR_OK && res.data.list.length > 0) {
    // list.value = [...list.value, ...res.data.list]
    if (props.selecOptionList.length > 0) {
      list.value = some(deteleObject([...list.value, ...res.data.list, ...props.selecOptionList]))
    } else {
      list.value = [...list.value, ...res.data.list]
    }
  } else {
    canmore.value = false
  }
  loading.value = false
}

const changeValue = (val) => {
  blurvalue.value = val
  let obj = {}
  list.value.forEach((item) => {
    if (val == item[props.selectObj.keyValue]) {
      obj = item
    }
  })
  // obj[props.selectObj.keyName] 获取的中文值
  // props.selectObj.assignmentName 业务需要的中文字段

  emit('update:modelValue', val)

  emit('pageChange', val, props.selectObj.assignment, obj[props.selectObj.keyName], props.selectObj.assignmentName, obj)
}

if (props.selectObj.opsName && (props.selectObj.opsValue || props.selectObj.opsValue === 0)) {
  // 编辑页面的回显
  nextTick(() => {
    // this.listObj[this.selectObj.keyName] = this.selectObj.opsName
    Object.assign(listObj, { [props.selectObj.keyName]: props.selectObj.opsName })
    // this.listObj[this.selectObj.keyValue] = this.selectObj.opsValue
    Object.assign(listObj, { [props.selectObj.keyValue]: props.selectObj.opsValue })
    if (JSON.stringify(listObj) != '{}') {
      list.value.push(listObj)
    }
  })
}

watch(
  () => props.modelValue,
  (newValue, oldValue) => {
    selectValue.value = newValue
  },
  { deep: true }
)

const params = computed(() => {
  // 传参模板
  return Object.assign(
    {
      keyName: '', // option的key
      keyValue: '', // option的value的key
      opsName: '', //  编辑回显list数据option的key的值
      opsValue: '', // 编辑回显list数据option的value的key的值
      Url: '', // 请求地址
      assignment: '', // 父级页面的赋值的key -form表单里的telAreaCode
      disabled: false, // 是否可以禁用
      clearable: false, // 是否可以清空
      params: {
        // 下拉框接口的传值
        // empNum: '', // 用户编码
        // empName: '', // 用户姓名
        // phone: '', // 手机号
        // email: '',
        // officeStatus: '', // 任职状态：实习，试用，在职，交接，离职
        // enabledFlag: true, // 状态：1-启用；0-未启用
        // associateFlag: '' //  是否已关联用户：true已关联；false未关联
      }
    },
    props
  )
})

const vSelectLoadMore = {
  mounted: (el, binding) => {
    nextTick(() => {
      // 获取element-ui定义好的scroll盒子
      // const selectDom = el.querySelector('.el-select-dropdown__wrap')
      const selectDom = document.getElementsByClassName('selectChild')
      for (var i = 0; i < selectDom.length; i++) {
        const tDom = selectDom[i].querySelector('.el-select-dropdown__wrap')
        tDom.addEventListener(
          'scroll',
          function() {
            const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight
            if (CONDITION) {
              binding.value()
            }
          },
          true
        )
      }
    })
  }
}
</script>

<style>
.w100 {
  width: 100%;
}
.loading {
  width: 100%;
  text-align: center;
  color: #606266;
  height: 34px;
  line-height: 34px;
  font-size: 14px;
}
.opsSpan {
  max-width: 360px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
